package sesi.ejava.stream;

import sesi.ejava.bcam.R;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

/**
 * This class allows the user to connect with a bluetooth device. If the user is
 * not connected, he can push upon a button that list the available devices
 * 
 * 
 * @author Cesar Fuguet
 * 
 */
public class BluetoothManager extends Activity {

	public static final int CONNECTED_DEVICE = 0;
	public static final int REQUEST_ENABLE_BLUETOOTH = 1;

	private BluetoothAdapter bluetoothAdapter;
	private TextView connectedDevice;
	private Button buttonListDevices;
	private BluetoothManagerService bluetoothManagerService;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Log.d("BluetoothManager", "onCreate()");

		setContentView(R.layout.bluetooth_manager_layout);

		connectedDevice = (TextView) findViewById(R.id.txtConnectedDevice);
		// if(bluetoothManagerService == null) {
		// connectedDevice.setText(R.string.NoConnectedDevice);
		// } else {
		// connectedDevice.setText(txtConnectedDevice);
		// }

		buttonListDevices = (Button) findViewById(R.id.buttonListDevices);
		buttonListDevices.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Intent listDevicesIntent = new Intent(v.getContext(),
						ListDevices.class);

				startActivityForResult(listDevicesIntent, CONNECTED_DEVICE);
			}
		});

		// If the adapter is null, then Bluetooth is not supported
		bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
		if (bluetoothAdapter == null) {
			Toast.makeText(this, R.string.txtBluetoothNoAvailable,
					Toast.LENGTH_LONG).show();
			finish();
			return;
		}
	}

	@Override
	protected void onStart() {
		super.onStart();
		Log.d("BluetoothManager", "onStart()");

		// If the bluetooth is not on, request that it be enabled.
		if (!bluetoothAdapter.isEnabled()) {
			Intent enableIntent = new Intent(
					BluetoothAdapter.ACTION_REQUEST_ENABLE);
			startActivityForResult(enableIntent, REQUEST_ENABLE_BLUETOOTH);
		} else {
			bluetoothManagerService = BluetoothManagerService.getInstance();
			bluetoothManagerService.setHandler(handler);
			bluetoothManagerService.setContext(this);

			if (bluetoothManagerService.isConnected()) {
				connectedDevice.setText(bluetoothManagerService
						.getConnectedDevice());
			} else {
				connectedDevice.setText(R.string.NoConnectedDevice);
			}
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		Log.d("BluetoothManager", "onResume()");

		bluetoothManagerService = BluetoothManagerService.getInstance();
		bluetoothManagerService.setHandler(handler);
		bluetoothManagerService.setContext(this);

		if (bluetoothManagerService.isConnected()) {
			connectedDevice.setText(bluetoothManagerService
					.getConnectedDevice());
		} else {
			connectedDevice.setText(R.string.NoConnectedDevice);
		}
	};

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		Log.d("BluetoothManager", "onActivityResult()");
		switch (requestCode) {
		// User had chose a bluetooth remote device
		case CONNECTED_DEVICE:
			if (resultCode == Activity.RESULT_OK) {
				String address = data.getExtras().getString(
						ListDevices.EXTRA_DEVICE_ADDRESS);

				// Get the BLuetoothDevice object
				BluetoothDevice device = bluetoothAdapter
						.getRemoteDevice(address);

				// Attempt to connect to the device
				bluetoothManagerService.connect(device);
			}
			break;

		case REQUEST_ENABLE_BLUETOOTH:
			// When the request to enable Bluetooth returns
			if (resultCode == Activity.RESULT_OK) {
				// Bluetooth is now enabled, so set up a chat session
				bluetoothManagerService = BluetoothManagerService.getInstance();
				bluetoothManagerService.setHandler(handler);
				bluetoothManagerService.setContext(this);

			} else {
				// User did not enable Bluetooth or an error occured
				Toast.makeText(this, R.string.txtBluetoothNoAvailable,
						Toast.LENGTH_SHORT).show();
				finish();
			}
		}
	}

	// The Handler that gets information back from the BluetoothChatService
	private final Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			String toastMessage;

			switch (msg.what) {
			case BluetoothManagerService.MESSAGE_TOAST:
				toastMessage = msg.getData().getString(
						BluetoothManagerService.TOAST);

				Toast.makeText(getApplicationContext(), toastMessage,
						Toast.LENGTH_SHORT).show();
				break;
			case BluetoothManagerService.MESSAGE_DEVICE_NAME:
				// save the connected device's name
				String txtConnectedDevice = msg.getData().getString(
						BluetoothManagerService.DEVICE_NAME);

				connectedDevice.setText(txtConnectedDevice);

				toastMessage = getString(R.string.ConnectionEstablished);
				Toast.makeText(getApplicationContext(), toastMessage,
						Toast.LENGTH_SHORT).show();
				break;
			}
		}
	};
}
